
#ifndef __ME32G030_I2C_H_
#define __ME32G030_I2C_H_

#ifdef __cplusplus
extern "C" {
#endif
#include "me32g030.h"
//I2C mode
	
/*
 * @brief I2C Control Set register description
 */
#define I2C_CONSET_AA             ((0x04))/*!< Assert acknowledge flag */
#define I2C_CONSET_SI             ((0x08))/*!< I2C interrupt flag */
#define I2C_CONSET_STO            ((0x10))/*!< STOP flag */
#define I2C_CONSET_STA            ((0x20))/*!< START flag */
#define I2C_CONSET_I2CEN           ((0x40))/*!< I2C interface enable */
#define I2C_CONSET_I2CINTEN           ((0x80))/*!< I2C interrupt enable */
/*
 * @brief I2C Control Clear register description
 */
#define I2C_CONCLR_AAC            (0x04)	/*!< Assert acknowledge Clear bit */
#define I2C_CONCLR_SIC            (0x08)	/*!< I2C interrupt Clear bit */
//#define I2C_CONCLR_STOC           ((1 << 4))	/*!< I2C STOP Clear bit */
#define I2C_CONCLR_STAC           (0x20)	/*!< START flag Clear bit */
#define I2C_CONCLR_I2ENC          ((1 << 6))	/*!< I2C interface Disable bit */

/*
 * @brief I2C Status Code definition (I2C Status register)
 */
#define I2C_STAT_CODE_BITMASK       ((0xF8))/*!< Return Code mask in I2C status register */
#define I2C_STAT_CODE_ERROR         ((0xFF))/*!< Return Code error mask in I2C status register */

/*
 * @brief I2C Master transmit mode
 */
#define I2C_BUS_ERROR													0				/* Bus Error */
#define I2C_STAT_M_TX_START                   ((0x08))/*!< A start condition has been transmitted */
#define I2C_STAT_M_TX_RESTART                 ((0x10))/*!< A repeat start condition has been transmitted */
#define I2C_STAT_M_TX_SLAW_ACK                ((0x18))/*!< SLA+W has been transmitted, ACK has been received */
#define I2C_STAT_M_TX_SLAW_NACK               ((0x20))/*!< SLA+W has been transmitted, NACK has been received */
#define I2C_STAT_M_TX_DAT_ACK                 ((0x28))/*!< Data has been transmitted, ACK has been received */
#define I2C_STAT_M_TX_DAT_NACK                ((0x30))/*!< Data has been transmitted, NACK has been received */
#define I2C_STAT_M_TX_ARB_LOST                ((0x38))/*!< Arbitration lost in SLA+R/W or Data bytes */

/*
 * @brief I2C Master receive mode
 */
#define I2C_STAT_M_RX_START                   ((0x08))/*!< A start condition has been transmitted */
#define I2C_STAT_M_RX_RESTART                 ((0x10))/*!< A repeat start condition has been transmitted */
#define I2C_STAT_M_RX_ARB_LOST                ((0x38))/*!< Arbitration lost */
#define I2C_STAT_M_RX_SLAR_ACK                ((0x40))/*!< SLA+R has been transmitted, ACK has been received */
#define I2C_STAT_M_RX_SLAR_NACK               ((0x48))/*!< SLA+R has been transmitted, NACK has been received */
#define I2C_STAT_M_RX_DAT_ACK                 ((0x50))/*!< Data has been received, ACK has been returned */
#define I2C_STAT_M_RX_DAT_NACK                ((0x58))/*!< Data has been received, NACK has been returned */

/*
 * @brief I2C Slave receive mode
 */
#define I2C_STAT_S_RX_SLAW_ACK                ((0x60))/*!< Own slave address has been received, ACK has been returned */
#define I2C_STAT_S_RX_ARB_LOST_M_SLA          ((0x68))/*!< Arbitration lost in SLA+R/W as master */
// #define I2C_I2STAT_S_RX_SLAW_ACK				((0x68)) /*!< Own SLA+W has been received, ACK returned */
#define I2C_STAT_S_RX_GENCALL_ACK             ((0x70))/*!< General call address has been received, ACK has been returned */
#define I2C_STAT_S_RX_ARB_LOST_M_GENCALL      ((0x78))/*!< Arbitration lost in SLA+R/W (GENERAL CALL) as master */
// #define I2C_I2STAT_S_RX_GENCALL_ACK				((0x78)) /*!< General call address has been received, ACK has been returned */
#define I2C_STAT_S_RX_PRE_SLA_DAT_ACK         ((0x80))/*!< Previously addressed with own SLA; Data has been received, ACK has been returned */
#define I2C_STAT_S_RX_PRE_SLA_DAT_NACK        ((0x88))/*!< Previously addressed with own SLA;Data has been received and NOT ACK has been returned */
#define I2C_STAT_S_RX_PRE_GENCALL_DAT_ACK     ((0x90))/*!< Previously addressed with General Call; Data has been received and ACK has been returned */
#define I2C_STAT_S_RX_PRE_GENCALL_DAT_NACK    ((0x98))/*!< Previously addressed with General Call; Data has been received and NOT ACK has been returned */
#define I2C_STAT_S_RX_STA_STO_SLVREC_SLVTRX   ((0xA0))/*!< A STOP condition or repeated START condition has been received while still addressed as SLV/REC (Slave Receive) or
														   SLV/TRX (Slave Transmit) */

/*
 * @brief I2C Slave transmit mode
 */
#define I2C_STAT_S_TX_SLAR_ACK                ((0xA8))/*!< Own SLA+R has been received, ACK has been returned */
#define I2C_STAT_S_TX_ARB_LOST_M_SLA          ((0xB0))/*!< Arbitration lost in SLA+R/W as master */
// #define I2C_I2STAT_S_TX_SLAR_ACK				((0xB0)) /*!< Own SLA+R has been received, ACK has been returned */
#define I2C_STAT_S_TX_DAT_ACK                 ((0xB8))/*!< Data has been transmitted, ACK has been received */
#define I2C_STAT_S_TX_DAT_NACK                ((0xC0))/*!< Data has been transmitted, NACK has been received */
#define I2C_STAT_S_TX_LAST_DAT_ACK            ((0xC8))/*!< Last data byte in I2DAT has been transmitted (AA = 0); ACK has been received */

#define I2C_STAT_S_TX_LAST_DAT_NACK 					0xD0 //	Last byte transmitted in slave mode, Not ACK received
#define I2C_STAT_SEC_ADDR_ACK									0xE0 //	Second Address byte transmitted, ACK received
#define I2C_STAT_SEC_ADDR_NACK								0xE8 //	Second Address byte transmitted, Not ACK received


#define I2C_SLAVE_TIME_OUT                      0x10000000UL/*!< Time out in case of using I2C slave mode */


/***************************** I2C Master *******************************/
typedef struct {
	uint8_t slaveAddr;		/*!< 7-bit I2C Slave address */
	uint8_t options;		/*!< Options for transfer*/
	uint16_t status;		/*!< Status of the current I2C transfer */
	uint16_t txSz;			/*!< Number of bytes in transmit array,
							   if 0 only receive transfer will be carried on */
	uint16_t rxSz;			/*!< Number of bytes to received,
							   if 0 only transmission we be carried on */
	uint8_t *txBuff;	/*!< Pointer to array of bytes to be transmitted */
	uint8_t *rxBuff;		/*!< Pointer memory where bytes received from I2C be stored */
} I2C_XFER_Type;
/**
 * @brief	Initialize I2C Interface
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function enables the I2C clock.
 */
void I2C_Init(I2C0_Type *i2c);

/**
 * @brief	Shutdown I2C Interface
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function disables the I2C clock.
 */
void I2C_DeInit(I2C0_Type *i2c);



/**
 * @brief	Set up bus speed for LPC_I2C controller
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	busSpeed	: I2C bus clock rate
 * @return	Nothing
 * @note	Per I2C specification the busSpeed should be
 *          @li 100000 for Standard mode
 *          @li 400000 for Fast mode
 *          @li 1000000 for Fast mode plus
 *          IOCON registers corresponding to I2C pads should be updated
 *          according to the bus mode.
 */
void I2C_Master_SetBusSpeed(I2C0_Type *i2c, uint32_t busSpeed);

/**
 * @brief	Transmit START or Repeat-START signal on I2C bus
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function sets the controller to transmit START condition when
 *          the bus becomes free.
 */
#define I2C_Master_SendStart(i2c)	i2c->CONSET = I2C_CONSET_I2CEN | I2C_CONSET_STA


/**
 * @brief	Reset I2C controller state
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function clears all control/status flags.
 */
#define I2C_Master_ResetControl(i2c)	i2c->CONCLR = I2C_CONCLR_SI | I2C_CONCLR_STA | I2C_CONCLR_AA


/**
 * @brief	Transmit a single data byte through the I2C peripheral
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	data	: Byte to transmit
 * @return	Nothing
 * @note	This function attempts to place a byte into the UART transmit
 *			FIFO or transmit hold register regard regardless of UART state
 *
 */
#define I2C_Master_WriteByte(i2c, data) 	i2c->DAT = data


/**
 * @brief	Read a single byte data from the I2C peripheral
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	A single byte of data read
 * @note	This function reads a byte from the I2C receive hold register
 *			regardless of I2C state. The I2C status should be read first prior
 *			to using this function.
 */
#define I2C_Master_ReadByte(i2c)	i2c->DAT


/**
 * @brief	Generate NACK after receiving next byte
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function sets the controller to NACK after receiving next
 *          byte from slave transmitter. Used before receiving last byte.
 */
#define  I2C_Master_NackNextByte(i2c)	i2c->CONCLR = I2C_CONCLR_AA

/**
 * @brief	Transmit STOP signal on I2C bus
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function sets the controller to transmit STOP condition.
 */
#define I2C_Master_SendStop(i2c)	i2c->CONSET = I2C_CONSET_STO


/**
 * @brief	Force start I2C transmit
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function forces I2C state machine to start transmitting.
 *			If an uncontrolled source generates a superfluous START or masks
 *          a STOP condition, then the I2C-bus stays busy indefinitely. If
 *          the STA flag is set and bus access is not obtained within a
 *          reasonable amount of time, then a forced access to the I2C-bus is
 *          possible. This is achieved by setting the STO flag while the STA
 *          flag is still set. No STOP condition is transmitted.
 */
#define  I2C_Master_ForceStart(i2c) 	\
	if (i2c->CONSET & I2C_CONSET_STA) 	\
		i2c->CONSET = I2C_CON_STO;				\
	else 														\
		I2C_Master_SendStart(i2c);		
/**
 * @brief	Transmit STOP+START signal on I2C bus
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note	This function sets the controller to transmit STOP condition
 *          followed by a START condition.
 */
#define   I2C_Master_SendStartAfterStop(i2c)	i2c->CONSET = I2C_CONSET_STO | I2C_CONSET_STA


/**
 * @brief	Check if I2C controller state changed
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Returns 0 if state didn't change
 * @note
 */
#define I2C_StateChanged(i2c)	i2c->CONSET & I2C_CONSET_SI


/**
 * @brief	Clear state change interrupt flag
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note
 */
#define  I2C_ClearSI(i2c) 	i2c->CONCLR = I2C_CONCLR_SI | I2C_CONCLR_STA

/**
 * @brief	Check if I2C bus is free per our controller
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Returns 0 if busy else a non-zero value.
 * @note	I2C controller clears STO bit when it sees STOP
 *          condition after a START condition on the bus.
 */
#define   I2C_BusFree(i2c) !(i2c->CONSET & I2C_CON_STO)


/**
 * @brief	Get current state of the I2C controller
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Returns 0 if busy else a non-zero value.
 * @note	I2C controller clears STO bit when it sees STOP
 *          condition after a START condition on the bus.
 */
#define  I2C_GetCurState(i2c) i2c->STAT & I2C_STAT_CODE_BITMASK

/**
 * @brief	Disable I2C interface
 * @param	i2c	: Pointer to selected I2C peripheral
 * @return	Nothing
 * @note
 */
#define  I2C_Disable(i2c)	i2c->CONCLR = I2C_CONCLR_I2EN


/**
 * @brief	Transfer state change handler handler
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	xfer	: Pointer to a I2CM_XFER_T structure see notes below
 * @return Returns non-zero value on completion of transfer. The @a status
 *         member of @a xfer structure contains the current status of the
 *         transfer at the end of the call.
 * @note
 * The parameter @a xfer should be same as the one passed to I2C_Master_Xfer()
 * routine.
 */
uint32_t I2C_Master_XferHandler(I2C0_Type *i2c, I2C_XFER_Type *xfer);

/**
 * @brief	Transmit and Receive data in master mode
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	xfer	: Pointer to a I2CM_XFER_T structure see notes below
 * @return Nothing.
 * @note
 * The parameter @a xfer should have its member @a slaveAddr initialized
 * to the 7-Bit slave address to which the master will do the xfer, Bit0
 * to bit6 should have the address and Bit8 is ignored. During the transfer
 * no code (like event handler) must change the content of the memory
 * pointed to by @a xfer. The member of @a xfer, @a txBuff and @a txSz be
 * initialized to the memory from which the I2C must pick the data to be
 * transferred to slave and the number of bytes to send respectively, similarly
 * @a rxBuff and @a rxSz must have pointer to memory where data received
 * from slave be stored and the number of data to get from slave respectively.
 * Following types of transfers are possible:
 * - Write-only transfer: When @a rxSz member of @a xfer is set to 0.
 *
 *          S Addr Wr [A] txBuff0 [A] txBuff1 [A] ... txBuffN [A] P
 *
 *      - If I2CM_XFER_OPTION_IGNORE_NACK is set in @a options member
 *
 *          S Addr Wr [A] txBuff0 [A or NA] ... txBuffN [A or NA] P
 *
 * - Read-only transfer: When @a txSz member of @a xfer is set to 0.
 *
 *          S Addr Rd [A] [rxBuff0] A [rxBuff1] A ... [rxBuffN] NA P
 *
 *      - If I2CM_XFER_OPTION_LAST_RX_ACK is set in @a options member
 *
 *          S Addr Rd [A] [rxBuff0] A [rxBuff1] A ... [rxBuffN] A P
 *
 * - Read-Write transfer: When @a rxSz and @ txSz members of @a xfer are non-zero.
 *
 *          S Addr Wr [A] txBuff0 [A] txBuff1 [A] ... txBuffN [A]
 *              S Addr Rd [A] [rxBuff0] A [rxBuff1] A ... [rxBuffN] NA P
 *
 */
void I2C_Master_Xfer(I2C0_Type *i2c, I2C_XFER_Type *xfer);

/**
 * @brief	Transmit and Receive data in master mode
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	xfer	: Pointer to a I2CM_XFER_T structure see notes below
 * @return Returns non-zero value on successful completion of transfer.
 * @note
 * This function operates same as I2C_Master_Xfer(), but is a blocking call.
 */
uint32_t I2C_Master_XferBlocking(I2C0_Type *i2c, I2C_XFER_Type *xfer);

/**
 * @brief	Write given buffer of data to I2C interface
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	buff	: Pointer to buffer to be transmitted
 * @param	len     : Length of the buffer
 * @return	Returns number of bytes written.
 * @note	This function is a blocking call. The function generates
 *          START/repeat-START condition on bus and starts transmitting
 *          data until transfer finishes or a NACK is received. No
 *          STOP condition is transmitted on the bus.
 *
 *          S Data0 [A] Data1 [A] ... DataN [A]
 */
uint32_t I2C_Master_Write(I2C0_Type *i2c, const uint8_t *buff, uint32_t len);

/**
 * @brief	Read data from I2C slave to given buffer
 * @param	i2c	: Pointer to selected I2C peripheral
 * @param	buff	:   Pointer to buffer for data received from I2C slave
 * @param	len     : Length of the buffer
 * @return	Returns number of bytes read.
 * @note	This function is a blocking call. The function generates
 *          START/repeat-START condition on bus and starts reading
 *          data until requested number of bytes are read. No
 *          STOP condition is transmitted on the bus.
 *
 *          S [Data0] A [Data1] A ... [DataN] A
 */
uint32_t I2C_Master_Read(I2C0_Type *i2c, uint8_t *buff, uint32_t len);



/***************************** I2C Slave **************************************************/
/**
 * @brief	I2C interface IDs
 * @note
 * All Chip functions will take this as the first parameter,
 * I2C_NUM_INTERFACE must never be used for calling any Chip
 * functions, it is only used to find the number of interfaces
 * available in the Chip.
 */
typedef enum I2C_ID {
	I2C0_ID,				/**< ID I2C0 */
	I2C1_ID,				/**< ID I2C1 */
	I2C_NUM_INTERFACE	/**< Number of I2C interfaces in the chip */
} I2C_ID_T;
typedef enum {
	I2C_SLAVE_GENERAL,	/**< Slave ID for general calls */
	I2C_SLAVE_0,		/**< Slave ID fo Slave Address 0 */
	I2C_SLAVE_1,		/**< Slave ID fo Slave Address 1 */
	I2C_SLAVE_2,		/**< Slave ID fo Slave Address 2 */
	I2C_SLAVE_3,		/**< Slave ID fo Slave Address 3 */
	I2C_SLAVE_NUM_INTERFACE	/**< Number of slave interfaces */
} I2C_SLAVE_ID;
/**
 * @brief	I2C master events
 */
typedef enum {
	I2C_EVENT_WAIT = 1,	/**< I2C Wait event */
	I2C_EVENT_DONE,		/**< Done event that wakes up Wait event */
	I2C_EVENT_LOCK,		/**< Re-entrency lock event for I2C transfer */
	I2C_EVENT_UNLOCK,	/**< Re-entrency unlock event for I2C transfer */
	I2C_EVENT_SLAVE_RX,	/**< Slave receive event */
	I2C_EVENT_SLAVE_TX,	/**< Slave transmit event */
} I2C_EVENT_T;

/**
 * @brief	Return values for SLAVE handler
 * @note
 * Chip drivers will usally be designed to match their events with this value
 */
#define RET_SLAVE_TX    6	/**< Return value, when 1 byte TX'd successfully */
#define RET_SLAVE_RX    5	/**< Return value, when 1 byte RX'd successfully */
#define RET_SLAVE_IDLE  2	/**< Return value, when slave enter idle mode */
#define RET_SLAVE_BUSY  0	/**< Return value, when slave is busy */
/**
 * @brief	I2C transfer status
 */
typedef enum {
	I2C_STATUS_DONE,	/**< Transfer done successfully */
	I2C_STATUS_NAK,		/**< NAK received during transfer */
	I2C_STATUS_ARBLOST,	/**< Aribitration lost during transfer */
	I2C_STATUS_BUSERR,	/**< Bus error in I2C transfer */
	I2C_STATUS_BUSY,	/**< I2C is busy doing transfer */
	I2C_STATUS_SLAVENAK,/**< NAK received after SLA+W or SLA+R */
} I2C_STATUS_T;
/* Set OWN slave address for specific slave ID */
void setSlaveAddr(I2C0_Type *i2c, I2C_SLAVE_ID sid, uint8_t addr, uint8_t mask);

/* Match the slave address */
int isSlaveAddrMatching(uint8_t addr1, uint8_t addr2, uint8_t mask);

/* Get the index of the active slave */
I2C_SLAVE_ID lookupSlaveIndex(I2C0_Type *i2c, uint8_t slaveAddr);

/* Find the slave address of SLA+W or SLA+R */
I2C_SLAVE_ID getSlaveIndex(I2C0_Type *i2c);

/* Slave state machine handler */
int handleSlaveXferState(I2C0_Type *i2c, I2C_XFER_Type *xfer);

 #ifdef __cplusplus
}
#endif

#endif /* __ME32G030_I2C_H_ */
